package vip.zhonghui.www.skills

import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

object Http {
    val client = OkHttpClient.Builder()
        .connectTimeout(10,TimeUnit.SECONDS)
        .readTimeout(10,TimeUnit.SECONDS)
        .writeTimeout(10,TimeUnit.SECONDS)
        .build()
    val baseURl = "https://mock.w2code.com/api/"
    fun post(url:String,json:JSONObject,callback:(String)->Unit){
        val body = RequestBody.create("application/json;charset=utf-8".toMediaType(),json.toString())
        val request = Request.Builder().url(baseURl+url).post(body).build()
        val call = client.newCall(request)
        call.enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                callback(e.message.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.let { callback(it.string()) }
            }

        })
    }
    fun get(url:String,callback:(String)->Unit){
        val request = Request.Builder().url(baseURl+url).build()
        val call = client.newCall(request)
        call.enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                callback(e.message.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                response.body?.let { callback(it.string()) }
            }

        })
    }
}